﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using MVVM.Core;

namespace ObjectModel.PowerPoint.New
{
    // A mutable key-value pair implementation that ensures that it's key
    // remains unique in it's parent collection after it is changed.
    public class UniqueKeyValuePair<TKey, TValue> : NotificationBase
    {
        TKey _key;
        TValue _value;

        public UniqueKeyValuePair() { }

        public UniqueKeyValuePair(TKey key, TValue value)
        {
            Key = key;
            Value = value;
        }

        public virtual TKey Key
        {
            get { return _key; }
            set
            {
                // Check whether an object with the same key already exists in
                // the parent collection.
                if (ParentCollection != null && ParentCollection.Any(o => o.Key.Equals(value)))
                    throw new InvalidOperationException("Key already exists.");

                _key = value;
                OnPropertyChanged("Key");
            }
        }

        public virtual TValue Value
        {
            get { return _value; }
            set
            {
                _value = value;
                OnPropertyChanged("Value");
            }
        }

        [XmlIgnore]
        public IEnumerable<UniqueKeyValuePair<TKey, TValue>> ParentCollection { get; set; }
    }
}
